package cn.doctor.assistant.pad.im;

import android.app.Application;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.easemob.EMConnectionListener;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMChatOptions;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;

import java.util.ArrayList;
import java.util.List;

import cn.doctor.assistant.pad.MyApplication;
import cn.doctor.assistant.pad.entity.ContactInfo;
import cn.doctor.assistant.pad.entity.GroupsBean;
import cn.doctor.assistant.pad.ui.hudong.IContantSelectedListener;

/**
 * IM即时通讯相关
 */
public class IMApplication extends Application {
    private static final String TAG = "jzsn";
    Context appContext;
    HXNotifier hxNotifier = null;

    protected String hxId;

    public void setHxId(String hxId) {
        this.hxId = hxId;
    }

    public String getHxId() {
        return this.hxId;
    }

    // 联系人
    List<GroupsBean> groups = new ArrayList<>();

    public void setGroups(List<GroupsBean> groups) {
        this.groups = groups;
    }

    public List<GroupsBean> getGroups() {
        return groups;
    }

    public ContactInfo getContact(String username) {
        for (int i = 0; i < groups.size(); i++) {
            if (groups.get(i).getUsers() != null) {
                for (int j = 0; j < groups.get(i).getUsers().size(); j++) {
                    ContactInfo contactInfo = groups.get(i).getUsers().get(j);
                    if (contactInfo.getPhone().equals(username)) {
                        return contactInfo;
                    }
                }
            }
        }
        return null;
    }

    //------------------聊天对象改变、更新UI---------------
    private List<IContantSelectedListener> mContactSelectedListeners = new ArrayList<>();

    public void addContactSelectedListener(IContantSelectedListener listener) {
        if (!mContactSelectedListeners.contains(listener)) {
            mContactSelectedListeners.add(listener);
        }
    }

    public void removeContactSelectedListener(IContantSelectedListener listener) {
        if (mContactSelectedListeners.contains(listener)) {
            mContactSelectedListeners.remove(listener);
        }
    }

    public void onSelectedContactChanged(ContactInfo user) {
        for (IContantSelectedListener listener : mContactSelectedListeners) {
            listener.onSelected(user);
        }
    }
    //----------------------------------------------------

    @Override
    public void onCreate() {
        super.onCreate();
        appContext = this;
        EMChat.getInstance().init(this);
        // 是否Debug模式，Release版最好设置为false，提升性能
        EMChat.getInstance().setDebugMode(true);
        EMChatOptions options = EMChatManager.getInstance().getChatOptions();

        //true表示使用环信的好友体系
        options.setUseRoster(false);

        options.setNotificationEnable(true);
        options.setNoticeBySound(true);
        options.setNoticedByVibrate(false);
        options.setUseSpeaker(true);

        //通知栏提醒
        hxNotifier = new HXNotifier();
        hxNotifier.init(this);
        hxNotifier.setNotificationInfoProvider(new HXNotifier.HXNotificationInfoProvider() {

            @Override
            public String getTitle(EMMessage message) {
                return null;
            }

            @Override
            public int getSmallIcon(EMMessage message) {
                return 0;
            }

            @Override
            public Intent getLaunchIntent(EMMessage message) {
                /*Log.i("jlf", message.toString());
                Intent it = new Intent(UI.getCurrActivity(), SimpleChatActivity.class);
                it.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                it.putExtra("friend", message.getFrom());
//				it.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                return it;*/
                return null;
            }

            @Override
            public String getLatestText(EMMessage message, int fromUsersNum,
                                        int messageNum) {
                return message.getFrom() + ":" + ((TextMessageBody) message.getBody()).getMessage();
            }

            @Override
            public String getDisplayedText(EMMessage message) {
                return null;
            }
        });

        //新消息监听
        EMChatManager.getInstance().registerEventListener(new EMEventListener() {

            @Override
            public void onEvent(EMNotifierEvent event) {
                Log.d("jzsn", "event:" + event.getEvent() + "," + event.getData());

                EMMessage message = null;
                if (event.getData() instanceof EMMessage) {
                    message = (EMMessage) event.getData();
                }

                switch (event.getEvent()) {
                    case EventNewMessage: {
                        // 修改消息（医生发来的消息，也显示在和患者聊天的界面中）
                        messageFilter(message);

                        hxNotifier.onNewMsg(message);
                        MyApplication.getInstance().notifyNewMessage(event.getEvent(), message);
                        break;
                    }

                    case EventDeliveryAck: {
                        message.setDelivered(true);
                        break;
                    }

                    case EventReadAck: {
                        message.setAcked(true);
                        break;
                    }

                    // add other events in case you are interested in
                    default:
                        break;
                }
            }
        });

        //连接监听
        EMChatManager.getInstance().addConnectionListener(new EMConnectionListener() {
            @Override
            public void onConnected() {
                Log.d("jzsn", "连接成功");
            }

            @Override
            public void onDisconnected(int i) {
                Log.d("jzsn", "连接失败");
            }
        });

    }

    // 医生转发过来的消息，就是医生和患者对话，real_receive_id就是指的患者。
    // senderId就是医生了。assisId,顾名思义，就是自己
    // 患者转发过来的消息，就是患者在和医生聊天,real_receive_id就是指的医生。
    // senderId就是患者了。assisId,还是自己
    private void updateMessageToDB(String msgid, String real_receice_id, String senderId, String assisId) {
        String dbName = hxId + "_emmsg.db";
        SQLiteDatabase sqlDB = MyApplication.getInstance().getCurrentActivity().openOrCreateDatabase(dbName, 0, null);

        boolean isFromDoctor = senderId.equals(MyApplication.getInstance().mCurrDoctor.getLogin_name());

        // 修改chat表中的数据
        Cursor cursor = sqlDB.query("chat", null, "msgid = ?", new String[]{msgid}, null, null, null);
        if (cursor.moveToNext()) {
            String original_msgbody = cursor.getString(9);
            //String msg2 = msg1.replaceFirst("\"to\":\"\\d{11}", "\"to\":\"" + receiveId);
            String midified_msgbody = null;

            // 当前是医生端发来的消息， from和to都要修改。（from要给成自己，to要改成患者）
            if (isFromDoctor) {
                midified_msgbody = original_msgbody.replaceFirst("\"from\":\"\\d{11}", "\"from\":\"" + MyApplication.getInstance().getHxId());
                midified_msgbody = midified_msgbody.replaceFirst("\"to\":\"\\d{11}", "\"to\":\"" + real_receice_id);
                Log.d("jzsn", midified_msgbody);
            }

            ContentValues values = new ContentValues();
            values.put("msgdir", isFromDoctor ? 0 : 1); // 0为发出的消息 1为接收的消息
            if (isFromDoctor) {
                values.put("msgbody", midified_msgbody);
            }
            values.put("participant", isFromDoctor ? real_receice_id : senderId);
            sqlDB.update("chat", values, "msgid = ?", new String[]{msgid});
            cursor.close();
        }

        if (isFromDoctor) {
            // 删掉和医生的会话
            sqlDB.delete("conversation_list", "username = ?", new String[]{senderId});
            // 删掉和医生的未读消息个数
            sqlDB.delete("unreadcount", "username = ?", new String[]{senderId});
        }

        // 与患者对话的未读消息个数加1
        String patientId = isFromDoctor ? real_receice_id : senderId;
        Cursor unreadCursor = sqlDB.query("unreadcount", null, "username = ?", new String[]{patientId}, null, null,
                null, null);
        if (unreadCursor.getCount() == 0) {
            ContentValues values = new ContentValues();
            values.put("username", patientId);
            values.put("count", 1);
            sqlDB.insert("unreadcount", null, values);
        } else {
            sqlDB.execSQL("update unreadcount set count = (count+1) where username = " + patientId);
        }
    }

    // true 过滤掉 ，false 不过滤
    private void messageFilter(EMMessage message) {
        // 直接发出的消息不含扩展字段。转发的消息，含有扩展字段。
        String msg_type = message.getStringAttribute("msg_type", null);
        String receive_id = message.getStringAttribute("real_receive_id", null);
        String sender_id = message.getStringAttribute("show_sender_id", null);

        if (msg_type != null && sender_id != null) {
            if (msg_type.equals("app")) {
                Log.d("jzsn", "pad:" + message.getBody());

                updateMessageToDB(message.getMsgId(), receive_id, sender_id, message.getFrom());
            }
        }
    }

}
